<?php
namespace app\controller;

use support\Db;
use support\Request;
use support\Response;

class UserController
{
    /**
     * 不需要登录的方法
     */
    protected array $noNeedLogin = ['login','doLogin'];

    public array $loginStatus = [0=>"offline",1=>"online",2=>"hide"];

    /**
     * 登录页
     * @param Request $request
     * @return Response
     */
    public function login(Request $request): Response
    {
        $user = Db::table("yi_user")->orderByDesc("id")->select("id","username")->get();
        return view("user/login",["user"=>$user]);
    }

    /**
     * 登录
     * @param Request $request
     * @return Response
     */
    public function doLogin(Request $request): Response
    {
        $post = $request->post();
        if ($post && isset($post["id"]) && isset($post["username"]) && isset($post["avatar"]) && isset($post["sign"]) && isset($post["status"])) {
            $request->session()->set('user', $post);
            return json(["code"=>0]);
        }
        return json(["code"=>1]);
    }

    /**
     * 登出
     * @param Request $request
     * @return Response
     */
    public function logout(Request $request): Response
    {
        $request->session()->flush();
        return json(["code"=>0]);
    }


    /**
     * 获取当前用户的好友列表
     * @param Request $request
     * @return Response
     */
    public function getFriendList(Request $request): Response
    {
        //
        $user = $request->session()->get("user");
        $user["status"] = $this->loginStatus[$user["status"]];

        //获取朋友列表
        $list[0] = [
          "id"        => 0,
          "groupname" => "我的好友",
          "online"    => 0,
          "list"      => [],
        ];

        $friend = Db::table("yi_friend")
                  ->join("yi_user", "yi_friend.friend_id", "=", "yi_user.id")
                  ->join("yi_friend_group", "yi_friend_group.id", "=", "yi_friend.friend_group_id", "left")
                  ->where("yi_friend.user_id", $user["id"])
                  ->where("yi_friend.status", 0)
                  ->select("yi_user.*", "yi_friend_group.groupname", "yi_friend_group.id as group_id")
                  ->get()
                  ->map(function ($value) {return (array)$value;})
                  ->toArray();
        if ($friend) {
            foreach ($friend as $val) {
                $group_id =  0;
                $group_name =  "我的好友";

                if ($val["group_id"]) {
                    $group_id   = $val["group_id"];
                    $group_name = $val["groupname"];
                }
                if (!isset($list[$group_id])) {
                    $list[$group_id]["id"]        = $group_id;
                    $list[$group_id]["groupname"] = $group_name;
                    $list[$group_id]["online"]    = 1;
                }
                $list[$group_id]["list"][] = [
                  "id"       => $val["id"],
                  "username" => $val["username"],
                  "avatar"   => $val["avatar"],
                  "sign"     => $val["sign"],
                ];
            }
            $friend = null;
        }

        //我加入的群组
        $group = Db::table("yi_group_member")
                  ->join("yi_group", "yi_group_member.group_id","=","yi_group.id")
                  ->where("yi_group_member.user_id", $user["id"])
                  ->select("yi_group.*")
                  ->get()
                  ->map(function ($value) {return (array)$value;})
                  ->toArray();
        //
        return json([
          "code" => 0,
          "msg"  => "ok",
          "data" => [
            "mine"    => $user,
            "friend"  => $list ?? [],
            "group"   => $group,
          ]
        ]);
    }

    /**
     * 获取指定群的群员列表
     * @param Request $request
     * @return Response
     */
    public function getGroupUserList(Request $request): Response
    {
        $group_id = $request->get("id");
        $list =  Db::table("yi_group_member")
                  ->join("yi_user", "yi_group_member.user_id", "=", "yi_user.id")
                  ->select("yi_user.*")
                  ->where("yi_group_member.group_id", $group_id)
                  ->orderByDesc("yi_group_member.user_status")
                  ->get()
                  ->map(function ($value) {return (array)$value;})
                  ->toArray();
        $members = [
            "code" => 0,
            "msg"  => "ok",
            "data" => [
              "owner" => $request->session()->get("user"),
              "list"  => $list,
            ]
        ];
        return json($members);
    }

    /**
     * 更改用户信息
     * @param Request $request
     * @return Response
     */
    public function setField(Request $request): Response
    {
        $data = [];
        $post = $request->post();
        $user = $request->session()->get("user");
        switch ($post["type"]) {
            case "online":
                $data["status"] = $user["status"] = $post["val"] == "online" ? 1 : 2;
                break;
            case "sign":
                $data["sign"] = $user["sign"] = $post["val"];
                break;
        }
        Db::table("yi_user")->where("id", $user["id"])->update($data);
        $request->session()->set("user", $user);
        return json(["code"=>0]);
    }

    /**
     * 查找好友 群
     * @return array
     */
    public function find(Request $request): Response
    {
        $mine = $request->session()->get("user");

        //用户列表
        $friend = Db::table("yi_friend")->where("user_id", $mine["id"])->pluck("friend_id");
        if ($friend) {
            $friend[] = $mine["id"];
        } else {
            $friend = [$mine["id"]];
        }
        $user = Db::table("yi_user")->select("id","username","avatar")->whereNotIn("id", $friend)->limit(16)->get()->map(function ($value) {return (array)$value;})->toArray();

        //群列表
        $myGroup = Db::table("yi_group_member")->where("user_id", $mine["id"])->pluck("group_id");
        if ($myGroup) {
            $group = Db::table("yi_group")->select("id","groupname","avatar")->whereNotIn("id", $myGroup)->limit(16)->get()->map(function ($value) {return (array)$value;})->toArray();
        } else {
            $group = Db::table("yi_group")->select("id","groupname","avatar")->limit(16)->get()->map(function ($value) {return (array)$value;})->toArray();
        }

        return view("user/find", [
          "user"  => $user ?: [],
          "group" => $group ?: []
        ]);
    }

    public function findList(Request $request)
    {
        $post  = $request->post();
        $where = $rows = $ids = [];
        $mine  = $request->session()->get("user");
        $post["id"] && $where[] = ["id", "=", (int)$post["id"]];
        switch ($post["t"]) {
            case 1:
                $post["name"] && $where[] = ["username", "like", "%{$post["name"]}%"];
                $rows = Db::table("yi_user")->select("id","username AS name","avatar")->where($where)->get()->map(function ($value) {return (array)$value;})->toArray();
                $ids = Db::table("yi_friend")->where("user_id", $mine["id"])->pluck("friend_id")->toArray();
                break;
            case 2:
                $post["name"] && $where[] = ["groupname", "like", "%{$post["name"]}%"];
                $rows = Db::table("yi_group")->select("id","groupname AS name","avatar")->where($where)->get()->map(function ($value) {return (array)$value;})->toArray();
                $ids = Db::table("yi_group_member")->where("user_id", $mine["id"])->pluck("group_id")->toArray();
                break;
        }
        return json_encode([
          "data" => $rows ?: [],
          "ids"  => $ids ?: []
        ]);
    }

    /**
     * 消息盒子
     * @return void
     */
    public function notice(Request $request): Response
    {
        return view("user/msg");
    }

    public function getNotice(Request $request)
    {
        $mine = $request->session()->get("user");
        $page = ($request->get("page") ?: 1) - 1;
        $limit = 30;

        $rows = Db::table("yi_system_message")
                  ->where("user_id", $mine["id"])
                  ->select("id","user_id","from_id","is_group","group_id","remark","type","status","time")
                  ->orderByDesc("id")
                  ->skip($page*$limit)
                  ->limit($limit)
                  ->get()
                  ->map(function ($value) {return (array)$value;})->toArray();

        if ($rows) {
            $user_id  = array_merge(array_column($rows, "user_id"), array_column($rows, "from_id"));
            $user_id  = array_unique($user_id);
            $user  = Db::table("yi_user")->whereIn("id", $user_id)->select("username","avatar", 'id')->get()->map(function ($value) {return (array)$value;})->toArray();
            if ($user) {
                foreach ($user as $k=>$v) {
                    unset($user[$k]);
                    $user[$v["id"]] = $v;
                }
            }

            $group_id = array_unique(array_column($rows, "group_id"));
            $group = Db::table("yi_group")->whereIn("id", $group_id)->pluck('groupname', 'id') ->map(function ($value) {return (array)$value;})->toArray();

            foreach ($rows as $k=>$v) {
                $to    = $user[$v["user_id"]]["username"] ?? "";
                $from  = $user[$v["from_id"]]["username"] ?? "";
                $groupname = $group[$v["group_id"]][0] ?? "";
                $diff = floor((time() - $v["time"]) / 86400);

                if ($diff > 5 && $v["status"] == 0) {
                    $v["status"] = 3;
                }

                $msg = $v["is_group"] == 0 ? "申请添加你为好友"  :  "申请加入群【{$groupname}】";
                if ($v["type"] == 1) {
                    switch ($v["status"]) {
                        case 2:
                            $msg = $v["is_group"] == 0 ? $from . "拒绝了你的好友申请" : $groupname . "：群主拒绝你的加群申请";
                            break;
                        case 1:
                            $msg = $v["is_group"] == 0 ? $from . "同意了你的好友申请" :  "【{$groupname}】群主同意了你的加群申请";
                            break;
                    }
                }
                $rows[$k]["status"]    = (int)$v["status"];
                $rows[$k]["username"]  = $from;
                $rows[$k]["groupname"] = $groupname;
                $rows[$k]["msg"]       = $msg;
                $rows[$k]["time"]      = $diff < 1 ? "刚刚" : "{$diff}天前";
                $rows[$k]["avatar"] = $user[$v["from_id"]]["avatar"] ?? "";
            }
            $user_id = $user = $group_id = $group = null;
        }
        return json(["code"=>0, "data"=>$rows, "total"=>30]);
    }

    public function read(Request $request)
    {
        $mine = $request->session()->get("user");
        Db::table("yi_system_message")
          ->where("user_id", $mine["id"])
          ->where("read",0)
          ->update(["read"=>1]);
    }

    /**
     * 聊天记录
     * @param Request $request
     * @return Response
     */
    public function chatlog(Request $request)
    {
        if (strtolower($request->method()) === "post") {
            $mine = $request->session()->get("user");
            $id = $request->post("id");

            $wh = "(yi_chat.user_id = {$mine['id']} AND yi_chat.to_id = {$id}) OR (yi_chat.to_id = {$mine['id']} AND yi_chat.user_id = {$id})";
            $list = Db::table("yi_chat")
                      ->join("yi_user", "yi_chat.user_id", "=", "yi_user.id")
                      ->whereRaw($wh)
                      ->select("yi_user.id","yi_user.username","yi_user.avatar","yi_chat.content",'yi_chat.create_at')
                      ->orderBy("yi_chat.id")
                      ->get()
                      ->map(function ($value) {return (array)$value;})
                      ->toArray();
            return json([
              "code" => 0,
              "msg" => "",
              "data" => $list,
            ]);
        }

        return view("user/chatlog");
    }
}